﻿using System;
using System.Web;
using Eneta.Portal.Common.Dto;
using Microsoft.SharePoint;

namespace Eneta.Portal.Common.Repository
{
    public class EmailTemplateRepository : BaseRepository
    {
        public EmailTemplateRepository(SPWeb currentWeb)
            : base(currentWeb)
        {         
        }

        public EmailTemplateDto GetEmailTemplateByName(string templateName)
        {
            EmailTemplateDto tpl = null;

            var sec = new SPSecurity.CodeToRunElevated(delegate
                {
                    using (var site = new SPSite(SiteId))
                    using (var web = site.OpenWeb())
                    {
                        var queryString = "<Where><Eq><FieldRef Name='Title' /><Value Type='String'>{0}</Value></Eq></Where>";
                        queryString = string.Format(queryString, templateName);

                        var query = new SPQuery();
                        query.Query = queryString;
                        query.RowLimit = 1;

                        if (!web.HasList("EmailTemplates"))
                        {
                            Logger.LogWarning("Cannot find list EmailTemplates");
                            return;
                        }

                        var list = web.Lists["EmailTemplates"];
                        var items = list.GetItems(query);

                        if (items.Count == 0)
                            return;

                        tpl = CreateEmailTemplate(items[0]);
                    }
                });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return tpl;
        }

        private EmailTemplateDto CreateEmailTemplate(SPListItem item)
        {
            if (item == null)
                return null;

            var dto = new EmailTemplateDto
                          {
                              Id = item.ID,
                              Title = item.Title,
                              Modified = (DateTime) item["Modified"],
                              Created = (DateTime) item["Created"],
                              BodyTemplate = item["TemplateBody"].ToString(),
                              TitleTemplate = item["TemplateTitle"].ToString()
                          };
            return dto;
        }
    }
}
